package com.zhangtao.demo.config.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class NioWebSocketServer {
    private static final Logger logger = LoggerFactory.getLogger(NioWebSocketServer.class);
    @PostConstruct
    public void init(){
        new Thread(() -> {
            logger.info("正在启动websocket服务器");
            NioEventLoopGroup boss=new NioEventLoopGroup();
            NioEventLoopGroup work=new NioEventLoopGroup();
            try {
                ServerBootstrap bootstrap=new ServerBootstrap();
                bootstrap.group(boss,work);
                bootstrap.channel(NioServerSocketChannel.class);
                bootstrap.childHandler(new NioWebSocketChannelInitializer());
                Channel channel = bootstrap.bind(8788).sync().channel();
                logger.info("webSocket服务器启动成功："+channel);
                channel.closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
                logger.info("运行出错："+e);
            }finally {
                boss.shutdownGracefully();
                work.shutdownGracefully();
                logger.info("websocket服务器已关闭");
            }
        }).start();
    }


}
